import print from 'print-js'
import { setEvent } from './utils'

export default function (options, delay = 0) {
  const event = setEvent()
  const dispatcher = setInterval(() => window.dispatchEvent(new Event(event)), 500)

  const onClose = options.onPrintDialogClose
  options.onPrintDialogClose = function () {
    clearInterval(dispatcher)
    typeof onClose === 'function' && onClose()
  }

  const onError = options.onError
  options.onError = function () {
    clearInterval(dispatcher)
    typeof onError === 'function' && onError()
  }

  setTimeout(() => {
    print(options)
  }, delay)
}
